var curTarget = null;
function createElement(text) {
  var element = document.createElement("textarea");
  //设置元素只读
  element.setAttribute("readonly", "");
  element.value = text;
  document.body.appendChild(element);
  return element;
}
// 监听来自 background.js sendContentScan 的消息
var getXPathForElement = (element) => {
  const allNodes = document.getElementsByTagName("*");
  for (
    let segs = [];
    element && element.nodeType === 1;
    element = element.parentNode
  ) {
    if (element.hasAttribute("id")) {
      let uniqueIdCount = 0;
      for (let n = 0; n < allNodes.length; n++) {
        if (allNodes[n].hasAttribute("id") && allNodes[n].id === element.id)
          uniqueIdCount++;
        if (uniqueIdCount > 1) break;
      }
      if (uniqueIdCount === 1) {
        segs.unshift(`id("${element.getAttribute("id")}")`);
        return segs.join("/");
      } else {
        segs.unshift(
          `${element.localName.toLowerCase()}[@id="${element.getAttribute(
            "id"
          )}"]`
        );
      }
    } else {
      let xPathIndex = 1;
      for (
        let sibling = element.previousSibling;
        sibling;
        sibling = sibling.previousSibling
      ) {
        if (sibling.nodeType === 1 && sibling.localName === element.localName)
          xPathIndex++;
      }
      const tagName = element.localName.toLowerCase();
      const nthChild = `[${xPathIndex}]`;
      segs.unshift(`${tagName}${nthChild}`);
    }
  }
  return segs.length ? `/${segs.join("/")}` : null;
};
chrome.runtime.onMessage.addListener(async function (
  request,
  sender,
  sendResponse
) {
  if (request.action === "sendContentScan") {
    let { text } = request.data;
    // 调用桌面通知
    var element = createElement(text);
    element.select();
    element.setSelectionRange(0, element.value.length);
    document.execCommand("copy");
    element.remove();
    sendResponse(`识别成功:${text},已复制到剪贴板`);
    return true;
  }
  if (request.action == "selectNode") {
    let { curForm, key } = request.data;
    console.log(request.data,'request.data;');
    
    let dict = {
      captchaPath: "img",
      inputPath: "input",
      buttonPath: "button",
    };

    let mask = null;
    const allowElements = [...document.querySelectorAll(dict[key])];
    let getXpath = await new Promise((resolve, reject) => {
      allowElements.forEach((element) => {
        let customMouseover = (event) => {
          if (mask) return;
          const target = event.target;
          curTarget = target;
          // 创建一个遮罩层
          mask = document.createElement("div");
          mask.classList.add("hx_mask");
          mask.style.position = "absolute";
          mask.style.top = `${event.clientY - event.offsetY}px`;
          mask.style.left = `${event.clientX - event.offsetX}px`;
          mask.style.width = `${target.clientWidth || target.width}px`;
          mask.style.height = `${target.clientHeight || target.height}px`;
          mask.style.backgroundColor = "rgba(0, 0, 0, 0.5)";
          mask.style.zIndex = "9999";
          mask.style.border = "2px dashed #8149c1";
          mask.addEventListener("mouseout", (event) => {
            [...document.querySelectorAll(".hx_mask")].forEach((i) => {
              i.remove();
            });
            // curTarget = null;
            mask = null;
          });
          mask.addEventListener("click", (event) => {
            allowElements.forEach((i) => {
              i.removeEventListener("mouseover", customMouseover);
            });
            [...document.querySelectorAll(".hx_mask")].forEach((i) => {
              i.remove();
            });
            mask = null;
            if (curTarget) {
              console.log(curTarget,'curTarget');
              
              // chrome.runtime.sendMessage(
              //   {
              //     action: "getXPath",
              //     data: {
              //       ...curForm.value,
              //       [key]: getXPathForElement(curTarget),
              //     },
              //   },
              //   (res) => {
              //     console.log(res, "res");
              //   }
              // );
              // resolve({
              //   ...curForm,
              //   [key]: getXPathForElement(curTarget),
              // });
            }
          });
          // 添加遮罩层到 body 中
          document.body.appendChild(mask);
        };
        element.addEventListener("mouseover", customMouseover);
      });
    });
    if (getXpath) {
      curTarget = null;
      chrome.runtime.sendMessage(
        { action: "changeConfItem", data: getXpath },
        function (response) {
          console.log("Response from popup:", response);
        }
      );
      sendResponse(getXpath);
      return true;
    }
  }
  if (request.action == "getXPath") {
    console.log(request, "request");
  }
});
